package com.z.service;

import java.util.List;
import java.util.UUID;

import com.z.dao.AccountDao;
import com.z.entity.Account;
import com.z.util.MD5;

public class RegisterService {
	private static RegisterService registerService;
	
	public static RegisterService getInstance(){
		if(registerService==null){
			registerService=new RegisterService();
		}
		return registerService;
	}
	
	/**
	 * 用户注册
	 * @param a VO
	 * @return
	 * 		0：注册成功；
	 * 		1：帐号已使用；
	 * 		2：密码加密错误；
	 */
	public int register(Account a){
		List<Account> all = AccountDao.getInstace().findAccounts(a.getAccount());
		if(all!=null&&all.size()>0){
			return 1;
		}
		
		Account account=new Account();
		account.setAccount(a.getAccount());
		account.setEmail(a.getEmail());
		account.setId(UUID.randomUUID().toString());
		account.setMale(a.isMale());
		account.setManager(false);
		account.setName(a.getName());
		try {
			account.setPassword(MD5.makeMD5(a.getPassword()));
		} catch (Exception e) {
			return 2;
		}
		AccountDao.getInstace().getDB().store(account);
		AccountDao.getInstace().getDB().commit();
		return 0;
	}
	
	public int checkManagerExisted(){
		return AccountDao.getInstace().checkManagerExisted();
	}
	
	/**
	 * 
	 * @param a 帐户信息
	 * @return
	 * 		0：成功；
	 * 		1：管理员已存在；
	 * 		2：登录名已被使用；
	 * 		3：密码加密发生错误；
	 * @see Account
	 */
	public int addManager(Account a){
		if(checkManagerExisted()==1){
			return 1;
		}
		List<Account> accounts = AccountDao.getInstace().findAccounts(a.getAccount());
		if(accounts!=null&&accounts.size()>0){
			return 2;
		}

		Account account=new Account();
		account.setAccount(a.getAccount());
		account.setEmail(a.getEmail());
		account.setId(UUID.randomUUID().toString());
		account.setMale(a.isMale());
		account.setManager(true);
		account.setName(a.getName());
		try {
			account.setPassword(MD5.makeMD5(a.getPassword()));
		} catch (Exception e) {
			return 3;
		}
		AccountDao.getInstace().getDB().store(account);
		AccountDao.getInstace().getDB().commit();
		return 0;
	}
	
	/**
	 * 检查帐户是否可用
	 * @param loginName 被检查的登录名
	 * @return
	 */
	public boolean checkAccountAvailable(String loginName){
		List<Account> accounts = AccountDao.getInstace().findAccounts(loginName);
		if(accounts!=null&&accounts.size()>0){
			return false;
		}
		return true;
	}
	
	public String findName(String id){
		return AccountDao.getInstace().findAccountName(id);
	}
}
